package com.iflytek.esb.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import com.iflytek.esb.dao.ConfigDao;
import com.iflytek.esb.domain.Config;

@Service
public class ConfigService {
	
	@Autowired
	private ConfigDao configDao;

	public String getJdbcProperty(String name) {
		return getProperty("jdbc.properties", name);
	}

	public void setJdbcProperty(String name, String value) {
		setProperty("jdbc.properties", name, value);
	}

	public String getLogProperty(String name) {
		return getProperty("log4j.properties", name);
	}

	public void setLogProperty(String name, String value) {
		setProperty("log4j.properties", name, value);
	}
	
	public String getConfigValue(String name) {
		Config config = configDao.getConfig(name);
		return config.getValue();
	}

	public void setConfigValue(String name, String value) {
		Config config = new Config();
		config.setName(name);
		config.setValue(value);
		
		configDao.updateConfig(config);
	}

	private String getProperty(String file, String name) {
		Properties props = new Properties();
		InputStream stream = null;
		try {
			ClassPathResource resource = new ClassPathResource(file);
			stream = resource.getInputStream();
			props.load(stream);
		}
		catch (IOException e) {
			//do nothind
		}
		finally {
			try {stream.close(); } catch (Exception e) {}
		}
		return props.getProperty(name);
	}

	private void setProperty(String file, String name, String value) {
		Properties props = new Properties();
		InputStream inputStream = null;
		//Writer writer = null;
		OutputStream outputStream = null;
		try {
			ClassPathResource resource = new ClassPathResource(file);
			inputStream = resource.getInputStream();
			props.load(inputStream);
			
			File f = resource.getFile();
			//writer = new FileWriter(file);
			outputStream = new FileOutputStream(f);
			
			if (StringUtils.startsWith(name, "log4j.logger.")) {
				//修改所有同样模式的值
				@SuppressWarnings("rawtypes")
				Enumeration keys = props.keys();
				while (keys.hasMoreElements()) {
					String key = String.valueOf(keys.nextElement());
					if (StringUtils.startsWith(key, "log4j.logger.")) {
						props.setProperty(key, value);
					}
				}
			}
			else {
				props.setProperty(name, value);
			}
			
			props.store(outputStream, "");
		}
		catch (IOException e) {
			//do nothind
		}
		finally {
			try {inputStream.close(); } catch (Exception e) {}
			//try {writer.close(); } catch (Exception e) {}
			try {outputStream.close(); } catch (Exception e) {}
		}
	}
}
